package com.lihonghao.classz;

import cn.hutool.core.thread.ThreadUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class 测试socket连接 {
    public static void main(String[] args) {
        String serverAddress = "127.0.0.1"; // 服务器地址
        int serverPort = 9527; // 服务器端口

        try (Socket socket = new Socket(serverAddress, serverPort);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
//             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             Scanner scanner = new Scanner(System.in)) {
//            socket.setSoTimeout(5000);
            System.out.println("已连接到服务器: " + serverAddress + ":" + serverPort);
            ThreadUtil.execute(() -> {

                while (true) {
                    if (socket.isClosed()) {
                        break;
                    }
                    try {
                        InputStream inputStream = socket.getInputStream();
                        byte[] bytes = new byte[1024];
                        int read = 0;
                        while (read != -1) {
                            read = inputStream.read(bytes);
                            if (read == -1) {
                                break;
                            }
                            String result = new String(bytes, 0, read);
                            System.err.println(result);
                            if (result.startsWith("{http_forward_channel}")){
                                out.println("back "+result);
                            }
                        }
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    ThreadUtil.sleep(1000);
                }

            });
            out.println("114514");
            while (true) {
                System.out.print("请输入要发送的消息（输入exit退出）: ");
                String userInput = scanner.nextLine();

                if ("exit".equalsIgnoreCase(userInput)) {
                    break;
                }

                out.println(userInput);
            }

        } catch (UnknownHostException e) {
            System.err.println("无法找到主机: " + serverAddress);
        } catch (IOException e) {
            System.err.println("I/O错误: " + e.getMessage());
        }
    }
}